<template>
	<view class="charging-container">
		<!-- 自定义导航栏 -->
		<custom-navbar title="首页"></custom-navbar>

		<!-- 地图区域 -->
		<view class="map-container" style="margin-top: 64px;">
			<map class="map" :latitude="latitude" :longitude="longitude" scale="14" :markers="markers" show-location>
			</map>

			<!-- 扫码按钮 -->
			<view class="scan-btn" @tap="scanQrCode">
				<image class="scan-icon" src="/static/tabbar/scan.png" mode="aspectFit"></image>
				<text class="scan-text">扫一扫</text>
			</view>

			<!-- 浮动的充电桩卡片 -->
			<view class="floating-card" style="margin-bottom: 180rpx;">
				<view class="charging-card">
					<view class="card-header">
					<view class="card-title">附近充电桩</view>
						<view class="card-badge">
							<text>推荐</text>
						</view>
					</view>
					<view class="station-info">
						<view class="station-details">
							<view class="station-name">科技园充电站</view>
							<view class="station-detail">
								<text class="distance">距离：1.2km</text>
								<text class="status">可用：5/8</text>
							</view>
						</view>
						<view class="nav-btn">导航</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 调试日志区域 -->
		<!--
		<view class="debug-container" :class="{ 'debug-collapsed': !showDebugLogs }">
			<view class="debug-header" @tap="toggleDebugLogs">
				<text>调试日志</text>
				<view class="debug-controls">
					<button v-if="showDebugLogs" class="clear-btn" @tap.stop="clearLogs">清空</button>
					<text class="debug-toggle">{{ showDebugLogs ? '收起' : '展开' }}</text>
				</view>
			</view>
			<scroll-view v-if="showDebugLogs" class="debug-content" scroll-y>
				<view v-for="(log, index) in debugLogs" :key="index" class="debug-log">
					<text>{{ log.time }}: </text>
					<text>{{ log.message }}</text>
				</view>
				<view v-if="debugLogs.length === 0" class="no-logs">暂无日志</view>
			</scroll-view>
		</view>
		-->

		<!-- 引入底部导航栏组件 -->
		<tab-bar></tab-bar>
	</view>
</template>

<script>
import TabBar from '@/components/TabBar.vue'  // 使用相对路径
import CustomNavbar from '@/components/CustomNavbar.vue'  // 导入自定义导航栏组件
import api from '@/src/api/index'
import { mapActions, mapState } from 'vuex'  // 导入 mapActions 和 mapState

export default {
	components: {
		TabBar,
		CustomNavbar
	},
	data() {
		return {
			latitude: 39.909, // 默认纬度
			longitude: 116.39742, // 默认经度
			markers: [], // 地图标记点
			homeData: null, // 首页数据
			loading: false, // 加载状态
			isLoggedIn: false, // 登录状态
			orderState: null, // 订单状态
			pileId: null, // 新增 pileId 属性
		}
	},
	computed: {
		...mapState('charger', ['pileId'])  // 映射 charger 模块的 pileId 状态
	},
	onLoad(options) {
		// 初始化调试日志
		// this.addLog('应用启动');


		if (options && options.scene) {
			let scene = decodeURIComponent(options.scene);
			// 解析scene参数
			let params = {};
			scene.split('&').forEach(item => {
				let parts = item.split('=');
				params[parts[0]] = parts[1];
			});

			// this.addLog('扫码参数:' + JSON.stringify(params));

			// 处理充电桩ID
			if (params.pileId) {
				// this.addLog('充电桩ID:' + params.pileId);
				// 保存充电桩ID到全局store
				this.setPileId(params.pileId);
				// this.addLog('已保存充电桩ID到全局store');
			}
		} else {
			// todo 测试使用
			// this.setPileId(123);
			// this.addLog('无扫码参数');
		}

		// this.checkLoginStatus();
	},
	onShow() {
		// 每次页面显示时检查登录状态
		this.checkLoginStatus();
		
		this.getCurrentLocation();
		this.fetchHomeData();


	},
	methods: {
		...mapActions('charger', ['setPileId', 'clearPileId']), // 映射 charger 模块的 actions

		// 添加日志方法
		/*
		addLog(message) {
			const now = new Date();
			const timeStr = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
			this.debugLogs.unshift({
				time: timeStr,
				message: message
			});
			// 保持日志数量不超过100条
			if (this.debugLogs.length > 100) {
				this.debugLogs.pop();
			}
			console.log(message);
		},
		*/

		// 切换调试日志显示状态
		toggleDebugLogs() {
			// this.showDebugLogs = !this.showDebugLogs;
		},

		// 清空日志
		clearLogs() {
			// this.debugLogs = [];
		},

		getOrderDetail() {
			// this.addLog('查询订单');
			console.log("查询订单");
			api.home.getOrderDetail().then(res => {
				// this.addLog("进入回调" + JSON.stringify(res));

				if (!res || !res.data) {
					// this.addLog("响应为空或无数据");
					console.log("响应为空或无数据");
					this.checkPileIdStatus();
					return;
				}

				const data = res.data;
				// this.addLog("返回数据:" + JSON.stringify(data));
				console.log("返回数据:" + JSON.stringify(data));
				if (data === null || !data.paymentStatus) {
					// this.addLog("无订单数据");
					this.checkPileIdStatus();
					return;
				}

				// this.addLog("进入方法");
				console.log("进入方法");
				const orderState = data.paymentStatus;
				// this.addLog(orderState + "订单的状态值是");
				console.log(orderState + "订单的状态值是");

				switch (orderState) {
					// 已支付
					case 0:
						// 检查充电桩ID状态
						this.checkPileIdStatus();
						return;
					// 待支付
					case 1:
						// 跳转支付页面
						uni.navigateTo({
							url: '/pages/paymentOrder/payment0rder'
						});
						break;
					// 进行中
					case 2:
						// 跳转进行中页面
						uni.navigateTo({
							url: '/pages/chargingProgress/chargingProgress'
						});
						break;
				}
			}).catch(err => {
				// this.addLog("请求错误:" + JSON.stringify(err));
				// 检查充电桩ID状态
				this.checkPileIdStatus();
			});
		},

		// 检查登录状态
		checkLoginStatus() {
			const token = uni.getStorageSync('token');
			this.isLoggedIn = !!token;
			// this.addLog('首页检查登录状态:' + this.isLoggedIn);
			if (!this.isLoggedIn) {
				this.goToLogin();
			} else {
				this.getOrderDetail();
			}
		},

		// 跳转到登录页
		goToLogin() {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		},

		getCurrentLocation() {
			uni.getLocation({
				type: 'gcj02', // 使用国测局坐标系
				success: (res) => {
					// this.addLog('获取位置成功' + JSON.stringify(res));
					this.latitude = res.latitude;
					this.longitude = res.longitude;

					// 设置当前位置标记
					this.markers = [{
						id: 1,
						latitude: res.latitude,
						longitude: res.longitude,
						iconPath: '/static/location.png', // 需要准备一个位置图标
						width: 30,
						height: 30
					},
					// 添加充电站标记点
					{
						id: 2,
						latitude: res.latitude + 0.01, // 示例：稍微偏移一点的位置
						longitude: res.longitude + 0.01,
						iconPath: '/static/charger.png', // 需要准备一个充电站图标
						width: 30,
						height: 30,
						callout: {
							content: '科技园充电站',
							color: '#000000',
							fontSize: 12,
							borderRadius: 4,
							padding: 5,
							display: 'ALWAYS'
						}
					}]
				},
				fail: (err) => {
					// this.addLog('获取位置失败' + JSON.stringify(err));
					uni.showToast({
						title: '获取位置失败，请检查定位权限',
						icon: 'none'
					});
				}
			});
		},

		// 获取首页数据
		fetchHomeData() {
			this.loading = true;
			// this.addLog('开始获取首页数据');

			// 使用模拟数据
			setTimeout(() => {
				const mockHomeData = {
					chargingStations: [
						{
							id: 1,
							name: '科技园充电站',
							latitude: this.latitude + 0.01,
							longitude: this.longitude + 0.01,
							availableCount: 5,
							totalCount: 8,
							distance: '1.2km'
						},
						{
							id: 2,
							name: '滨海大道充电站',
							latitude: this.latitude - 0.005,
							longitude: this.longitude + 0.015,
							availableCount: 3,
							totalCount: 6,
							distance: '2.5km'
						}
					],
					banners: [
						{
							id: 1,
							imageUrl: '/static/banner1.png',
							linkUrl: ''
						},
						{
							id: 2,
							imageUrl: '/static/banner2.png',
							linkUrl: ''
						}
					]
				};

				this.homeData = mockHomeData;
				// this.addLog('获取首页数据成功');

				// 更新地图标记
				if (mockHomeData.chargingStations && mockHomeData.chargingStations.length > 0) {
					// 保留当前位置标记
					const locationMarker = this.markers[0];

					// 添加充电站标记点
					const stationMarkers = mockHomeData.chargingStations.map((station, index) => {
						return {
							id: index + 10, // id从10开始，避免与当前位置冲突
							latitude: station.latitude,
							longitude: station.longitude,
							iconPath: '/static/charger.png',
							width: 30,
							height: 30,
							callout: {
								content: station.name,
								color: '#000000',
								fontSize: 12,
								borderRadius: 4,
								padding: 5,
								display: 'ALWAYS'
							}
						};
					});

					// 合并标记点
					this.markers = [locationMarker, ...stationMarkers];
					// this.addLog(`更新了${stationMarkers.length}个充电站标记`);
				}

				this.loading = false;
			}, 1000);
		},

		// 检查充电桩ID状态
		checkPileIdStatus() {
			// 从全局store中获取充电桩ID
			this.pileId = this.$store.state.charger.pileId;
			if (this.pileId) {
				// this.addLog('当前充电桩ID: ' + this.pileId);
				// 跳转开始充电页面，并携带充电桩ID
				uni.navigateTo({
					url: '/pages/start_charging/startCharging'
				});
			} else {
				// this.addLog('当前无充电桩ID');
				uni.showToast({
					title: '请扫码充电桩',
					icon: 'none'
				});
			}
		},

		scanQrCode() {
			// 调用扫码API
			uni.scanCode({
				scanType: ['qrCode', 'barCode'], // 扫码类型
				success: (res) => {
					console.log('扫码结果:', res);
					
					// 尝试解析扫码结果
					try {
						// 尝试提取充电桩ID
						let pileId = null;

						// 方案1: 直接从结果中提取数字ID
						if (/^\d+$/.test(res.result)) {
							pileId = res.result;
							console.log('直接提取到的ID:', pileId);
						} 
						// 方案2: 解析URL参数
						else if (res.result.includes('pileId=') || res.result.includes('pile_id=')) {
							// 提取URL中的参数，避免使用URL构造函数（小程序中可能不支持）
							try {
								// 获取查询字符串
								let queryString = res.result.split('?')[1];
								if (!queryString && res.result.includes('&')) {
									// 可能是纯参数字符串
									queryString = res.result;
								}
								
								// 解析参数
								if (queryString) {
									const params = {};
									queryString.split('&').forEach(param => {
										const [key, value] = param.split('=');
										if (key && value) {
											params[key] = value;
										}
									});
									
									// 尝试获取充电桩ID
									pileId = params['pileId'] || params['pile_id'];
									console.log('从URL参数中提取到的ID:', pileId);
								}
							} catch (e) {
								console.error('解析URL参数失败:', e);
							}
						} 
						// 方案3: 解析JSON格式
						else if (res.result.startsWith('{') && res.result.endsWith('}')) {
							try {
								const jsonResult = JSON.parse(res.result);
								pileId = jsonResult.pileId || jsonResult.pile_id || jsonResult.id;
								console.log('从JSON中提取到的ID:', pileId);
							} catch (e) {
								console.error('解析JSON失败:', e);
							}
						}

						// 方案4: 解析微信小程序码场景值
						else if (res.result.includes('scene=')) {
							try {
								// 从结果中提取scene参数
								const sceneMatch = res.result.match(/scene=([^&]+)/);
								if (sceneMatch && sceneMatch[1]) {
									// 解码scene参数
									const scene = decodeURIComponent(sceneMatch[1]);
									console.log('解码scene参数:', scene);
									
									// 解析scene字符串（通常是key=value&key=value格式）
									const sceneParams = {};
									scene.split('&').forEach(item => {
										const parts = item.split('=');
										if (parts.length === 2) {
											sceneParams[parts[0]] = parts[1];
										}
									});
									
									// 从scene中提取充电桩ID
									pileId = sceneParams.pileId || sceneParams.pile_id;
									console.log('从scene中提取到的ID:', pileId);
								}
							} catch (e) {
								console.error('解析scene参数失败:', e);
							}
						}

						// 如果提取到充电桩ID，则保存并跳转页面
						if (pileId) {
							// 保存充电桩ID到全局store
							this.setPileId(pileId);
							
							// 显示提示
							uni.showToast({
								title: '扫码成功',
								icon: 'success',
								duration: 1500
							});
							
							// 延迟跳转到充电页面
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/start_charging/startCharging'
								});
							}, 1500);
						} else {
							// 未能提取到充电桩ID，提示错误
							uni.showToast({
								title: '无效的二维码',
								icon: 'none',
								duration: 2000
							});
						}
					} catch (error) {
						console.error('处理扫码结果异常:', error);
						uni.showToast({
							title: '无法识别二维码内容',
							icon: 'none',
							duration: 2000
						});
					}
				},
				fail: (err) => {
					console.error('扫码失败:', err);
					// 用户取消扫码不提示错误
					if (err.errMsg !== 'scanCode:fail cancel') {
						uni.showToast({
							title: '扫码失败',
							icon: 'none',
							duration: 2000
						});
					}
				}
			});
		},

	}
}
</script>

<style lang="scss">
.charging-container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: #f6f8fa;

	.login-tip-container {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;

		.login-tip {
			background-color: rgba(25, 137, 250, 0.95);
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 16rpx 30rpx;

			.login-tip-text {
				color: #ffffff;
				font-size: 28rpx;
			}

			.login-now-btn {
				background-color: #ffffff;
				color: #1989fa;
				font-size: 24rpx;
				padding: 8rpx 20rpx;
				border-radius: 30rpx;
				margin: 0;
				min-height: 0;
				height: auto;
				line-height: 1.5;
			}
		}
	}

	.status-bar {
		background-color: #1989fa;
		padding: 20rpx;
		color: #fff;
		text-align: center;
		z-index: 10;
	}

	.map-container {
		flex: 1;
		position: relative;

		.map {
			width: 100%;
			height: 100%;
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
		}

		.scan-btn {
			position: absolute;
			right: 30rpx;
			bottom: 260rpx;
			z-index: 5;
			background-color: #1989fa;
			color: #fff;
			border-radius: 50rpx;
			padding: 20rpx 30rpx;
			display: flex;
			align-items: center;
			box-shadow: 0 6rpx 16rpx rgba(25, 137, 250, 0.25);
			transition: all 0.3s;
			
			&:active {
				transform: scale(0.96);
				background-color: #1778e3;
			}

			.scan-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}

			.scan-text {
				font-size: 28rpx;
				color: #fff;
			}
		}

		.floating-card {
			position: absolute;
			left: 30rpx;
			right: 30rpx;
			bottom: 40rpx;
			z-index: 5;
		}
	}

	.charging-card {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 24rpx 30rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
		transition: all 0.3s;
		
		&:active {
			transform: scale(0.98);
		}

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 24rpx;

		.card-title {
			font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}
			
			.card-badge {
				background-color: #ff6b6b;
				color: #fff;
				padding: 4rpx 14rpx;
				border-radius: 6rpx;
				font-size: 22rpx;
				font-weight: 500;
				position: relative;
				
				&::after {
					content: '';
					position: absolute;
					left: -6rpx;
					top: 50%;
					transform: translateY(-50%);
					border-width: 6rpx;
					border-style: solid;
					border-color: transparent #ff6b6b transparent transparent;
				}
			}
		}

		.station-info {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.station-details {
				flex: 1;
			}

			.station-name {
				font-size: 30rpx;
				margin-bottom: 12rpx;
				color: #333;
				font-weight: 500;
			}

			.station-detail {
				font-size: 24rpx;
				color: #666;
				display: flex;

				.distance {
					margin-right: 24rpx;
					display: flex;
					align-items: center;
					
					&::before {
						content: "";
						display: inline-block;
						width: 16rpx;
						height: 16rpx;
						background-color: #1989fa;
						border-radius: 50%;
						margin-right: 8rpx;
					}
				}
				
				.status {
					display: flex;
					align-items: center;
					
					&::before {
						content: "";
						display: inline-block;
						width: 16rpx;
						height: 16rpx;
						background-color: #4cd964;
						border-radius: 50%;
						margin-right: 8rpx;
					}
				}
			}

			.nav-btn {
				background-color: #1989fa;
				color: #fff;
				padding: 12rpx 32rpx;
				border-radius: 30rpx;
				font-size: 26rpx;
				margin-bottom: 20rpx;
				margin-right: 20rpx;
				font-weight: 500;
				display: flex;
				align-items: center;
				justify-content: center;
				min-width: 120rpx;
				box-shadow: 0 4rpx 12rpx rgba(25, 137, 250, 0.2);
				transition: all 0.3s;
				
				&:active {
					transform: scale(0.95);
					background-color: #1778e3;
				}
				
				&::before {
					content: "";
					display: inline-block;
					width: 24rpx;
					height: 24rpx;
					background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M22 12l-4-4v3H3v2h15v3z"/></svg>');
					background-size: contain;
					margin-right: 8rpx;
				}
			}
		}

		.pile-id-info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 14rpx 0;
			border-top: 1px solid #f0f0f0;
			margin-top: 14rpx;

			text {
				font-size: 24rpx;
				color: #666;
			}

			.clear-pile-btn {
				background-color: #ff6b6b;
				color: #fff;
				font-size: 22rpx;
				padding: 6rpx 20rpx;
				border-radius: 20rpx;
				margin: 0;
				line-height: 1.5;
				min-height: unset;
				height: auto;
				box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.2);
				transition: all 0.2s;
				
				&:active {
					transform: scale(0.95);
					background-color: #ff5252;
				}
			}
		}
	}

	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		justify-content: space-around;
		align-items: center;
		border-top: 1rpx solid #eee;
		z-index: 10;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

		.tab-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 10rpx 0;
			
			&.active {
				color: #1989fa;
			}

			image {
				width: 40rpx;
				height: 40rpx;
				margin-bottom: 6rpx;
			}

			text {
				font-size: 24rpx;
				color: #666;
				
				&.active {
					color: #1989fa;
				}
			}
		}
	}

	.debug-container {
		position: fixed;
		bottom: 100rpx;
		/* Position above the tab bar */
		left: 0;
		right: 0;
		z-index: 100;
		background-color: rgba(255, 255, 255, 0.95);
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		max-height: 400rpx;
		/* Maximum height */

		&.debug-collapsed {
			max-height: 60rpx;
		}

		.debug-header {
			background-color: #1989fa;
			padding: 10rpx 20rpx;
			color: #fff;
			font-size: 28rpx;
			font-weight: bold;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.debug-controls {
				display: flex;
				align-items: center;
			}

			.clear-btn {
				background-color: rgba(255, 255, 255, 0.3);
				color: #fff;
				font-size: 22rpx;
				padding: 4rpx 12rpx;
				border-radius: 20rpx;
				margin-right: 20rpx;
				line-height: 1;
				min-height: unset;
				height: auto;
			}

			.debug-toggle {
				color: #fff;
				font-size: 24rpx;
				background-color: rgba(255, 255, 255, 0.2);
				padding: 4rpx 12rpx;
				border-radius: 20rpx;
			}
		}

		.debug-content {
			height: 340rpx;
			overflow-y: auto;

			.debug-log {
				padding: 10rpx 20rpx;
				border-bottom: 1rpx solid #eee;
				font-size: 24rpx;
				line-height: 1.5;
				word-break: break-all;

				text:first-child {
					color: #1989fa;
					font-weight: bold;
				}
			}

			.no-logs {
				padding: 20rpx;
				text-align: center;
				font-size: 24rpx;
				color: #666;
			}
		}
	}
}
</style>